/*	
 * Authors: Ken YANG <spng.yang@gmail.com>
 * 	
 * Mammoth client main program
 *
 * Copyright (C) 2007-2008 Ken YANG
 * This program is free software; you can redistribute it and/or 
 * modify it under the terms of the GNU General Public License 
 * as published by the Free Software Foundation, version 2. 
 * THIS SOFTWARE COMES "AS IS" WITHOUT ANY WARRANTIES.
 */

#include "func_basic.h"

/* Fork wrapper, including error handle */
pid_t Fork(void)
{
	pid_t childpid;

	if((childpid=fork())==-1){
		err_sys("fork error");
	}
	return childpid;
}

void *Malloc(size_t size)
{
	void *ptr;
	
	if((ptr=malloc(size))==NULL)
		err_sys("malloc error");

	return ptr;
}

void *
Calloc(size_t n, size_t size)
{
        void *ptr;
	if((ptr = calloc(n, size)) == NULL)
		err_sys("calloc error");
	return(ptr);
}

int 
Fcntl(int fd, int cmd, int args)
{
	int rc;
	if((rc=fcntl(fd, cmd, args))<0)
		err_sys("fcntl error");
	return rc;
}


/* 
 * Simulate the semanic of old "signal()", using 
 * POSIX sigaction()
 *
 * */
Sigfunc *signal(int signo, Sigfunc *func)
{
	struct sigaction depo, olddepo;

	depo.sa_handler=func;
	sigemptyset(&depo.sa_mask);
	depo.sa_flags=0;
	if(signo==SIGALRM)
		depo.sa_flags |= SA_INTERRUPT;
	else
		depo.sa_flags |= SA_RESTART;

	if(sigaction(signo, &depo, &olddepo)<0)
		return(SIG_ERR);
	return(olddepo.sa_handler);
}

/* Above's wrapper */
Sigfunc *Signal(int signo, Sigfunc *func)
{
	Sigfunc *olddepo;
	if((olddepo=signal(signo, func))==SIG_ERR)
		err_sys("signal error");
	return(olddepo);
}

/* SIGCHLD signal handle */
void wait_chld(int signo)
{
	pid_t pid;
	int status;

	while((pid=waitpid(-1, &status, WNOHANG))>0){
		/* 
		 * just for debug, we should not use 
		 * printf in signal handle for the 
		 * non-reentrant reason
		 * */
		printf("child %d terminated\n",pid);
	}
	return;
}


/* Select wrapper */
int Select(int maxfdpl, fd_set *readset, fd_set *writeset,
		fd_set *exceptset, const struct timeval *timeout)
{
	int rc;
	if((rc=select(maxfdpl, readset, writeset, exceptset, 
					timeout))==-1)
		err_sys("select error");
	return rc;	/* can return 0 if time out */
}





